<template>
  <el-container>
    <el-card class="box-card">
      <el-form ref="form" :model="form" :rules="rules" label-width="0px">
        <el-form-item prop="name">
          <el-input placeholder="请输入用户名" prefix-icon="el-icon-user" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input placeholder="请输入密码" prefix-icon="el-icon-s-tools" v-model="form.password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login">登录</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-container>
</template>

<script>
  import axios from 'axios'
  export default {
    data() {
      return {
        form: {
          name: '',
          password: ''
        },
        rules: {
          name: [{
            required: true,
            message: '请输入用户名',
            trigger: 'blur'
          }, {
            min: 3,
            max: 5,
            message: '长度在 3 到 5 个字符',
            trigger: 'blur'
          }],
          password: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 5,
              message: '长度在 3 到 5 个字符',
              trigger: 'blur'
            }
          ]
        }
      }
    },
    methods: {
      login() {
        //校验, 参数valid是否校验成功
        /* this.$refs.form.validate(function(valid) {
          // console.log(valid);
          if(valid){
            //发送请求
          }
        }) */
        this.$refs.form.validate(async valid => {
          //校验失败,结束函数
          if (!valid) return;
          let {
            data: r
          } = await axios.post('/login', this.form);

          /* if (JSON.parse(r).code != 200) {
            this.$message.error('用户名或密码错误');
          } else {
            this.$router.push("/home");
          } */

          if (JSON.parse(r).code != 200)
            return this.$message.error('用户名或密码错误');
          const rs = {
            "nickname": JSON.parse(r).result.nickname,
            "apiKey": JSON.parse(r).result.apiKey
          }
          localStorage.setItem("rs", JSON.stringify(rs));
          // this.$router.push("/home");
        })
      },
      reset() {
        this.$refs.form.resetFields();
      }
    }
  }
</script>

<style scoped>
  .el-container {
    background-image: url(../assets/background.jpg);
    background-repeat: no-repeat;
    background-size: cover;
    height: 100%;
  }

  .el-card {
    width: 30%;
    position: absolute;
    left: 60%;
    top: 10%;
    height: 60%;
  }
</style>
